package com.dingwen.minser.exception;


import com.dingwen.minser.result.Result;
import com.dingwen.minser.result.ResultGenerator;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 * @author dingwen
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	@ResponseBody
	@ExceptionHandler(Exception.class)
	public Result globalException(HttpServletResponse response, Exception ex) {
		ex.printStackTrace();
		response.setStatus(500);
		Result r = ResultGenerator.genFailureResult(ex.getMessage());
		
		if(ex instanceof ServiceException) {
			r = ((ServiceException) ex).result();
		} else if (ex instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException e = (MethodArgumentNotValidException) ex;
			
			int i = 0;
			StringBuilder str = new StringBuilder("验证错误！");
			for(ObjectError error : e.getAllErrors()) {
				str.append(++i).append(". ").append(error.getDefaultMessage()).append(' ');
			}
			r = ResultGenerator.genFailureResult(str.toString());
		}
		
		return r;
	}
}